package com.atguigu.spzx.manager.auth;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.utils.ThreadLocalUtil;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取method请求方式,如果是OPTIONS(跨域请求的一个预测请求) 放行true
        String mehtod = request.getMethod();
        //预检性请求,直接放行  导致跨域问题
        if(mehtod.equals("OPTIONS")){
            return true;
        }
        //非预检行请求 得需要登录状态的校验 redis中查询token
        //2.从请求头获取token,为空证明没登录 用请求头保存的token 来保存redis中 在redis中获取token判断是否登录
        //3 前端将token存放在localStore
        String token = request.getHeader("token");
        //拼接key
        String key = "user:login:" + token;
        //redis查询key
        String jsonString = redisTemplate.opsForValue().get(key);
        //判断是否为空
        if(StringUtils.isEmpty(jsonString)){
            //响应json
           return this.response208(response);


        }
        //3.每次和后端进行交互时,都将过期时间恢复到30分钟 前提:该key得存在
        redisTemplate.expire(key,30, TimeUnit.MINUTES);

        //4.将用户信息存储到ThreadLocal 就不用再读取redis,直接读取ThreadLocal
        //添加一组key-value的数据 map中
        //new ThreadLocal<SysUser>().set(JSON.parseObject(jsonString, SysUser.class));
        ThreadLocalUtil.setSysUser(JSON.parseObject(jsonString, SysUser.class));


        System.out.println(ThreadLocalUtil.getSysUser());
        System.out.println("aop ...  " + Thread.currentThread().getName());
        return true;

    }

    private boolean response208(HttpServletResponse response){
        //2.非预检请求
        Result noLogin = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        String jsonResult208 = JSON.toJSONString(noLogin);

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");



        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        writer.write(jsonResult208);
        if(writer!=null){
            writer.close();
        }
        return false;
  }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //视图渲染之后(请求完全的处理结束)
        ThreadLocalUtil.removeSysUser();;
    }
}
